import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { DevToolBar, CpasIcon, DevGrid, DevPopup } from '~/public/cpas-ui';
import { Item } from 'devextreme-react/toolbar';
import { CheckBox, DataGrid, LoadIndicator, ScrollView, TextBox } from "devextreme-react";
import { accountAdjustCol, auditAdjustCol } from "./SimpleDatas"
// import AdjustEntry from "./components/AdjustEntry";
import { everyreCaljustBill, getBillList, getOneBillDetail, getOneBillDetailOfJZ, getReportItemsData, getRollBillListed, rollBills, ZBAdjustDel } from "./service";
import type { guid } from 'guid-factory/lib/Guid';
import { Guid } from 'guid-factory/lib/Guid';
import { useModel } from "umi";
import { throttle } from "lodash";
import notify from "devextreme/ui/notify";
import * as ReactDOMClient from 'react-dom/client';
// import AntdPopup from "./components/AntdPopup"
import "./index.less"
import { Pagination, Radio, Typography } from "antd";
// import EntryPopup from "./components/AdjustEntry/components/EntryPopup";
// import { subjectGetJZKM } from "./components/AdjustEntry/service";
import { subjectGetJZKM } from "./SpecificPupopFun/components/AdjustEntry/service";
import EntryPopup from "./SpecificPupopFun/components/AdjustEntry/components/EntryPopup";

import SpecificPupopFun from "./SpecificPupopFun";

import { ToolBarDataContext } from "../index";
import { intl, nanoid10 } from "@/utils";



const { Text } = Typography;

const AdjustGrid: React.FC<any> = React.forwardRef((props: any, ref: any) => {
    const { toolBarData, setToolBarData } = useContext<any>(ToolBarDataContext);
    const { whereFrom } = props;
    const { timesData } = toolBarData;
    const { initialState } = useModel('@@initialState');
    const { dbname, zcbfid } = initialState?.curPart as API.CurPart;
    const { username, usercode } = initialState?.curUser as API.CurUser;
    const SpecificPupopFunRef = useRef<any>();

    const { isShowGloablLoad, accountInfo, setIsShowGlobalLoad } = useModel('useAdjustModel');

    const DelteRef = useRef<any>();
    const BatchRollingRef = useRef<any>();
    const devGridRef = useRef<any>();
    const valueRadioRef = useRef<number>(1);
    const [valueRadio, setValueRadio] = useState<number>(1);
    const [gridDataList, setGridDataList] = useState<any[]>([]);
    const checkedItemsRef = useRef<any>(new Map());
    const batchBillIDRowsRef = useRef<any>([]);

    const [contentSettingData, setContentSettingData] = useState<any>({
        content: null,
        width: 80,
        height: 180,
        isRadio: false
    });
    const EntryPopupRef = useRef<any>();

    const [isBtnStutas, setIsBtnStutas] = useState<any>({
        isShowJZ: false,
        isShowDetail: false
    });

    // const { setIsShowGlobalLoad } = useModel('useAdjustModel');
    // const devIsTZRef = useRef<any>('');

    const changeContentSettingData = (tempData: any, tempWidth: number = 100, tempHeight: number = 180, tempIsRadio: boolean = false) => {
        setContentSettingData({
            content: tempData,
            width: tempWidth,
            height: tempHeight,
            isRadio: tempIsRadio
        });
    }

    const changeToolBarData = (changeData: any) => {
        setToolBarData((oldData: any) => {
            const newData = { ...oldData, ...changeData };
            return newData;
        });
    }
    const getBillListData = async (isFirstPage: boolean = true) => {
        if (!toolBarData.Data_ID) return;
        setIsShowGlobalLoad(true);
        // setBatchBillIDs([]);
        // setBatchBillIDRows([]);
        batchBillIDRowsRef.current = [];
        checkedItemsRef.current = new Map();
        // setGridDataList([]);
        // devIsTZRef.current = toolBarData.isTZ;
        console.log(whereFrom, {
            dbname,
            Data_ID: toolBarData.Data_ID,
            TZQJ: Number(toolBarData.TZQJ),
            isTZ: toolBarData.isTZ,
            // TZLX: toolBarData?.TZLX ?? "",
            ...isBtnStutas
        }, '@@@ 请求开始了。。。');

        console.time();
        devGridRef.current.instance.beginCustomLoading('数据加载中...');
        // setIsShowLoadIndicator(true);
        try {
            const res = await getBillList(whereFrom, {
                dbname,
                Data_ID: toolBarData.Data_ID,
                TZQJ: Number(toolBarData.TZQJ),
                isTZ: toolBarData.isTZ,
                // pageSize: requestPages.pageSize,
                // pageNum: isFirstPage ? 1 : requestPages.currentPage,
                // TZLX: toolBarData?.TZLX ?? "",
                ...isBtnStutas
            });
            if (res.success) {
                setGridDataList(res.data);
                devGridRef.current.instance.endCustomLoading();
                console.timeEnd();
                setIsShowGlobalLoad(false);
            } else {
                setIsShowGlobalLoad(false);
                setGridDataList([]);
                devGridRef.current.instance.endCustomLoading();
                notify("获取列表失败", "error", 2000);
            }
        } catch (error) {
            setIsShowGlobalLoad(false);
            setGridDataList([]);
            devGridRef.current.instance.endCustomLoading();
            notify("获取列表失败", "error", 2000);
        }
    }

    useEffect(() => {
        getBillListData();
    }, [isBtnStutas, timesData]);

    const getOneBillDetails = async () => {
        const myId: guid = Guid.newGuid();
        const resDetail = await getOneBillDetail(whereFrom, {
            dbname,
            billID: myId,
            isRefresh: false,
        });
        const resDetailOfJZ = await getOneBillDetailOfJZ(whereFrom, {
            dbname,
            billID: myId,
        });
        if (!resDetail.success) {
            notify(`getOneBillDetail,${resDetail.data}`, "error", 2000);
        }

        if (!resDetailOfJZ.success) {
            notify(`getOneBillDetailOfJZ,${resDetailOfJZ.data}`, "error", 2000);
        }
        return myId;
    };

    async function getReportItemsDatas() {
        const myId: guid = Guid.newGuid();
        // 获取某单据的表单信息
        await getReportItemsData(whereFrom, {
            dbname,
            billID: myId,
        });
    };

    const newAddFun = async (isAdd: boolean = false) => {
        const myId = await getOneBillDetails();
        if (whereFrom === '审计调整') {
            await getReportItemsDatas();
        }
        if (isAdd) {
            SpecificPupopFunRef.current.newAddDanJu({
                args: {
                    dataBillID: myId,
                    state: false,
                }
            })
        } else {
            SpecificPupopFunRef.current.show({
                args: {
                    title: `${whereFrom}分录`,
                    dataBillID: myId,
                    state: false,
                    Data_ID: toolBarData.Data_ID,
                    isTZQJ: toolBarData.TZQJ
                }
            });
        }

    };

    const DeleteClick = () => {
        let cheackIDs = [...checkedItemsRef.current.keys()];
        let batchBillIDs = batchBillIDRowsRef.current.map((item: any) => item.BillID);
        if (cheackIDs?.length) {
            DelteRef.current.show({
                title: "提示",
                okCallback: async () => {
                    const r = await ZBAdjustDel(whereFrom, {
                        dbname,
                        billIDs: batchBillIDs.join(";"),
                        editUser: username,
                        Data_ID: toolBarData.Data_ID,
                    })
                    if (r) {
                        batchBillIDRowsRef.current = [];
                        checkedItemsRef.current = new Map();
                        getBillListData();
                        notify('删除成功', 'success', 2000);
                    }
                }
            })
        } else {
            notify("请选择您要删除的单据", "warning", 2000)
        }
    };

    const batchChangeSelectData = useCallback(() => {
        batchBillIDRowsRef.current = [];
        checkedItemsRef.current = new Map();
        let isTZQJ = '';
        let isTZQJName = '';
        let isData_ID = '';

        if (toolBarData.TZQJ === "0") {
            isTZQJ = "1";
            isTZQJName = "期末";
        } else {
            isTZQJ = "0";
            isTZQJName = "期初";
        }
        isData_ID = toolBarData.TZQJ === "0" ? toolBarData.Data_ID : `${toolBarData.Data_ID * 1 + 1}`;
        let findTemp = -2;
        findTemp = accountInfo.findIndex((item: any) => {
            return isData_ID === item.Data_ID
        });
        const tempDisplayName = accountInfo[findTemp]?.displayName;
        changeToolBarData({ showYearName: tempDisplayName, Data_ID: isData_ID, TZQJ: isTZQJ, TZQJName: isTZQJName, timesData: `${new Date().getTime()}` });
    }, [toolBarData, accountInfo]);

    // 执行滚调
    const executeRollBills = async (tempBillID: any, tempRadio: any) => {
        const r = await rollBills(tempRadio, {
            dbname,
            billIDs: tempBillID,
            trueName: username,
            userCode: usercode
        });
        if (r.success) {
            const rTempData = r.data[0];
            if (rTempData?.isExistsNoneKM === 1) {
                notify("滚调的分录中存在不连续的科目，请自行修改！", "warning", 2000);
            } else {
                notify("滚调成功", "success", 2000);
            }
            // console.log('@@@', whereFrom, tempRadio);
            if (whereFrom === '账表调整' && tempRadio === 1 || whereFrom === '审计调整' && tempRadio === 2) {
                batchChangeSelectData();
            }
            const isData_ID = toolBarData.TZQJ === "0" ? toolBarData.Data_ID : `${toolBarData.Data_ID * 1 + 1}`;
            const res = await everyreCaljustBill({
                dbname,
                Data_ID: isData_ID,
                editUser: username,
                isRecalTZ: true
            });
            if (res.success) {
                notify('重算成功！', 'success', 2000)
            }
            return;
        }
        if (r?.data) {
            const msg = r?.data ?? 'r.data';
            const isName = typeof msg === 'string' ? msg?.includes("滚调的期间未设置结转科目") : false;
            if (isName) {
                settingZDJZKM(tempBillID, tempRadio);
                return;
            }

            if (msg.name === "RequestError") {
                notify('请求超时，请求未响应！', "warning", 2000);
            } else {
                notify(r.data, "error", 2000);
            }
        } else {
            notify('滚调失败！', "error", 2000);
        }
    };
    // 设置自动结转科目
    const settingZDJZKM = useCallback(async (tempData: any, tempRadio: any) => {
        const isData_ID = toolBarData.TZQJ === "0" ? toolBarData.Data_ID : `${toolBarData.Data_ID * 1 + 1}`;
        const res = await subjectGetJZKM({
            dbname,
            Data_ID: isData_ID
        });
        EntryPopupRef.current.show({
            args: {
                title: '设置自动结转科目',
                data: res,
                tipNotify: true
            },
            // 点击确定的回调函数 获取回掉数据时间节点返回需要的
            okCallback: async () => {
                // debugger;
                executeRollBills(tempData, tempRadio);
            },
        });
    }, [whereFrom, toolBarData]);

    const launchPopup = (tempData: any, tempBillID: string, tempRadio: any) => {
        changeContentSettingData(tempData, 300, 350, false);
        BatchRollingRef.current.show({
            title: "存在已滚调单据",
            okCallback: async () => {
                executeRollBills(tempBillID, tempRadio);
            },
            onCancel: () => {

            }
        });
    }

    const BatchClick = async () => {
        let cheackIDs = [...checkedItemsRef.current.keys()];
        let batchBillIDs = batchBillIDRowsRef.current.map((item: any) => item.BillID);

        if (cheackIDs.length === 0) return notify("请选择您要滚调的分组", "warning", 2000);
        changeContentSettingData("将滚调选中的调整分录单据,是否继续操作？", 100, 180, true);
        BatchRollingRef.current.show({
            title: "提示",
            okCallback: async () => {
                const billidsData = batchBillIDs.join(";");
                const res = await getRollBillListed({
                    dbname,
                    billIDs: billidsData
                });
                if (res.success) {
                    if (res.data?.length) {
                        const returnTemplate = () => {
                            return (
                                <ScrollView width='100%' height='100%'>
                                    <div>存在已滚调的单据，是否重复滚调？单据识别码:
                                        {
                                            res.data.map((item: any, index: number) => {
                                                return <div key={index}>【{item.billID}】</div>
                                            })
                                        }
                                    </div>
                                </ScrollView>
                            )
                        }
                        // console.log(whereFrom, valueRadioRef.current, '@@@ launchPopup');
                        launchPopup(returnTemplate(), billidsData, valueRadioRef.current);
                    } else {
                        // console.log(whereFrom, valueRadioRef.current, '@@@ executeRollBills');

                        executeRollBills(billidsData, valueRadioRef.current);
                    }
                }
            }
        })

    };
    const EntryEditClick = () => {
        let cheackIDs = [...checkedItemsRef.current.keys()];
        let batchBillIDs = batchBillIDRowsRef.current.map((item: any) => item.BillID);
        if (cheackIDs?.length !== 1) return notify("请选择一条您要编辑的单据", "warning", 2000);
        if (batchBillIDRowsRef.current[0]?.IsJZFL) return notify('该单据为损益结转分录，禁止编辑！', 'warning', 2000);
        SpecificPupopFunRef.current.show({
            args: {
                title: `${whereFrom}分录`,
                dataBillID: batchBillIDs.join(''),
                state: true,
                Data_ID: toolBarData.Data_ID,
                isTZQJ: toolBarData.TZQJ
            }
        });
    }

    const onCellDblClick = (e: any) => {
        if (e.rowType !== "group") {
            if (e.data?.IsJZFL) return notify('该单据为损益结转分录，禁止编辑！', 'warning', 2000);
            if (e.data) {
                SpecificPupopFunRef.current.show({
                    args: {
                        title: `${whereFrom}分录`,
                        dataBillID: e.data.BillID,
                        state: true,
                        Data_ID: toolBarData.Data_ID,
                        isTZQJ: toolBarData.TZQJ
                    }
                });
                //    setTimeout(() => {  }, 150);
            }
        }
    };

    const inputSearch = (content: any) => {
        devGridRef.current.instance.searchByText(content || "");
    };
    const throttleSearch = throttle(inputSearch, 100);
    const getInputValue = (e: any) => {
        const { event } = e;
        throttleSearch(event.target.value);
    };

    const onRadioChange = (e: any) => {
        setValueRadio(e.target.value);
        valueRadioRef.current = e.target.value;
    };

    // 显示隐藏期初列
    function customizeColumns(columns: any[]) {
        if (whereFrom === '账表调整') {
            columns.forEach(function (column: any) {
                if (column.dataField === 'IsJZFL') {
                    column.visible = isBtnStutas.isShowJZ;
                }
                return column;
            });

        } else {
            columns.forEach(function (column: any) {
                if ((column.dataField === 'AdjustType' || column.dataField === 'IsRetrospect') && toolBarData.TZQJ === '1') {
                    column.visible = false;
                } else {
                    column.visible = true;
                }
                if (column.dataField === 'IsJZFL') {
                    column.visible = isBtnStutas.isShowJZ;
                }
                return column;
            });
        }
        return columns;
    };

    const renderToolbar = (<div style={{ width: '100%', height: '36px', }}>
        <DevToolBar.Default style={{ height: '36px', }}  >
            <Item location="before">
                <div style={{ display: 'flex', alignItems: "center", justifyContent: "center" }}>
                    <div className="Text_style" onClick={() => newAddFun()}>
                        <div style={{ marginRight: '5px' }}>
                            <CpasIcon type='icon-add-circle' fontSize={16} />
                        </div>
                        <div>
                            新增调整
                        </div>
                    </div>
                    <div className="Text_style" onClick={DeleteClick}>
                        <div style={{ marginRight: '5px' }}>
                            <CpasIcon type='icon-delete' fontSize={16} />
                        </div>
                        <div>
                            删除调整
                        </div>
                    </div>
                    <div className="Text_style" onClick={EntryEditClick}>
                        <div style={{ marginRight: '5px' }}>
                            <CpasIcon type='icon-rename-copy' fontSize={16} />
                        </div>
                        <div>
                            编辑调整
                        </div>
                    </div>
                    <div className="Text_style" onClick={() => {
                        setValueRadio(1);
                        valueRadioRef.current = 1;
                        BatchClick();
                    }}>
                        <div style={{ marginRight: '5px' }}>
                            <CpasIcon type='icon-piliangguntiao' fontSize={16} />
                        </div>
                        <div>
                            批量滚调
                        </div>
                    </div>
                </div>
            </Item>
            <Item location="after">
                <span style={{ marginRight: '10px' }}><CheckBox text="显示自动结转分录" onValueChange={(e: any) => {
                    setIsBtnStutas((oldData: any) => {
                        return { ...oldData, isShowJZ: e }
                    });
                }} /></span>
                <span style={{ marginRight: '10px' }}><CheckBox text="显示所有分录明细" onValueChange={(e: any) => {
                    setIsBtnStutas((oldData: any) => {
                        return { ...oldData, isShowDetail: e }
                    });
                }} /></span>
            </Item>
            <Item location="after">
                <TextBox
                    width={200}
                    style={{ marginRight: '8px' }} onInput={(e: any) => getInputValue(e)}
                    className="TextBoxButtons_Style"
                    buttons={[
                        {
                            location: "before",
                            name: "search",
                            options: {
                                icon: "iconfont icon-search",
                                disabled: true,
                            },
                        },
                    ]}
                />  {/*  */}
            </Item>
            <Item location="after">
                <div className="IconRefresh_Style">
                    <CpasIcon type='icon-refresh' fontSize={16} onClick={() => {
                        getBillListData();
                    }} />
                </div>
            </Item>
        </DevToolBar.Default>
    </div>
    );

    const handleCheckboxChange = (itemId: any, valueCheck: boolean) => {
        const itemIdFun = (prevCheckedItems: Map<any, boolean>) => {
            let newCheckedItems = new Map(prevCheckedItems);
            if (valueCheck) {
                newCheckedItems.set(itemId, true);
            } else {
                newCheckedItems.delete(itemId);
            }
            return newCheckedItems;
        }
        checkedItemsRef.current = itemIdFun(checkedItemsRef.current);
    };

    const onCellClisckDeltes = (newData: any, isAdd: boolean) => {
        if (!newData.BillID) return;
        if (isAdd) {
            batchBillIDRowsRef.current.unshift(newData);
        } else {
            batchBillIDRowsRef.current = batchBillIDRowsRef.current.filter((item: any) => item.itemBillGUID != newData.itemBillGUID);
        }
    };

    const changeGrid = useMemo(() => {
        let dataGrid: any;
        let tempColumn: any = [{
            dataField: "GroupInfo",
            dataType: "string",
            caption: "组信息",
            width: 120,
            alignment: "center",
            groupIndex: 0,
            groupCellTemplate: (cellElement: any, options: any) => {
                const itemId = options.data.items ? options.data.items[0].itemBillGUID : options.data.collapsedItems[0].itemBillGUID;
                const isChecked = checkedItemsRef.current.get(itemId) || false;
                return ReactDOMClient.createRoot(cellElement).render(
                    <>
                        <div style={{ display: "flex", alignItems: "center" }}>
                            <CheckBox
                                className="SubjectsCheckBox"
                                defaultValue={isChecked}
                                onValueChanged={(e) => {
                                    handleCheckboxChange(itemId, e.value);
                                    if (options.data.items) {
                                        onCellClisckDeltes(options.data.items[0], e.value);
                                    } else {
                                        onCellClisckDeltes(options.data.collapsedItems[0], e.value);
                                    }
                                }}
                            />
                            <Text ellipsis={{ tooltip: options.value }} style={{ color: '#333' }}>
                                {options.value}
                            </Text>
                        </div>
                    </>
                );
            }
        }];

        if (whereFrom === '账表调整') {
            tempColumn = [...tempColumn, ...accountAdjustCol];
        } else {
            tempColumn = [...tempColumn, ...auditAdjustCol];
        };

        let tempKey = nanoid10();

        dataGrid = <DevGrid.RangeTap
            // dataGrid = <DataGrid
            className='PaperDevSortableGrid devHeadersCenter'
            ref={devGridRef}
            height='100%'
            width="100%"
            id="id"
            key={tempKey}
            dataSource={gridDataList}
            keyExpr="itemBillGUID"
            defaultColumns={tempColumn}
            sheetName="账表调整事项汇总表"
            excelName="账表调整事项汇总表"
            showBorders={true}
            showRowLines={true}
            showColumnLines={true}
            hoverStateEnabled={true}
            onCellDblClick={onCellDblClick}
            allowColumnResizing={true}
            columnResizingMode="widget"
            focusedRowEnabled={true}
            // onOptionChanged={(e) => {
            //     if (e.fullName === "paging.pageIndex") {
            //         setBatchBillIDs([]);
            //         setBatchBillIDRows([]);
            //     }
            // }}
            columnMinWidth={100}
            grouping={{
                autoExpandAll: true
            }}
            // onContentReady={(e) => {
            //     console.log(e, '@@@  开始渲染 页面了 ');
            //     setBatchBillIDs([]);
            //     setBatchBillIDRows([]);
            //     // setTimeout(() => {
            //     //     setIsShowGlobalLoad(false);
            //     // }, 1000);
            // }}
            filterPanel={{ visible: false }}
            filterRow={{ visible: false }}
            loadPanel={{
                enabled: true,
                text: '数据加载中...',
            }}
            scrolling={{
                mode: 'virtual',
                rowRenderingMode: 'standard',
                renderAsync: true,
            }}
            groupPanel={{
                visible: false
            }}
            paging={{
                enabled: false
            }}
            columnAutoWidth={true}
            customizeColumns={customizeColumns}
        />;

        // 客户有反馈问题，禁止分页。 分页产生的问题更多。 20241125
        // const { currentPage, pageSize, totalCount } = requestPages;
        return (<div style={{ width: '100%', height: "calc(100% - 45px)", marginTop: '8px' }} className="changeGridList">
            {dataGrid}
        </div>)
    }, [gridDataList, whereFrom]);

    return (
        <div style={{ position: "relative", width: '100%', height: '100%' }}>
            {isShowGloablLoad && <div style={{
                position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
                opacity: 0.5, zIndex: "999", background: "#ddd"
            }}>
                <LoadIndicator id="medium-indicator" height={50} width={50} />
            </div>}
            {renderToolbar}
            {changeGrid}
            <SpecificPupopFun ref={SpecificPupopFunRef}
                whereFrom={whereFrom}
                AddClickRef={newAddFun}
                refreshClick={() => {
                    getBillListData();
                }}
            />
            <EntryPopup ref={EntryPopupRef} width={500} height={300} AccountDataID={toolBarData.TZQJ === "0" ? toolBarData.Data_ID : `${toolBarData.Data_ID * 1 + 1}`} />
            <DevPopup.Default ref={DelteRef} width={80} height={220}  >
                {() => {
                    return <span>确定要执行此删除操作吗？</span>
                }}
            </DevPopup.Default>
            <DevPopup.Default ref={BatchRollingRef} width={contentSettingData.width} height={contentSettingData.height}  >
                {() => {
                    return <>
                        <div>{contentSettingData.content}</div>
                        {contentSettingData.isRadio && <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            // justifyContent: "space-between",
                            margin: '8px 5px'
                        }}>  滚调类型：
                            <Radio.Group onChange={onRadioChange} value={valueRadio} >
                                <Radio value={1}>账表调整</Radio>
                                <Radio value={2}>审计调整</Radio>
                            </Radio.Group>
                        </div>}
                    </>
                }}
            </DevPopup.Default>
        </div >
    )

});
export default AdjustGrid;

